﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace MyRssReader
{
    class RssProvider:System.Windows.Data.DataSourceProvider
    {
        private System.Uri _source;
        public System.Uri Source 
        {
            set
            {
                if (value == _source)
                    return;
                this._source = value;
                base.OnPropertyChanged(new System.ComponentModel.PropertyChangedEventArgs("Source"));
            }
            get
            {
                return _source;
            }
        }
    	protected override void BeginQuery()
        {
                base.OnQueryFinished(Channel.Load(this.Source).First<Channel>());
        }   
    }
    public class Channel
    {
        public string Title { set; get; }
        public string Link { set; get; }
        public string Description { set; get; }
        public IEnumerable<Item> Items { set; get; }
        public static IEnumerable<Channel> Load(System.Uri Url)
        {
            XDocument xDoc = XDocument.Load(Url.ToString());
            return from channels in xDoc.Descendants("channel")
                   select new Channel
                   {
                       Title = channels.Element("title") != null ? channels.Element("title").Value : "",
                       Link = channels.Element("link") != null ? channels.Element("link").Value : "",
                       Description = channels.Element("description") != null ? channels.Element("description").Value : "",
                       Items = from items in channels.Descendants("item")
                               select new Item
                               {
                                   Title = items.Element("title") != null ? items.Element("title").Value : "",
                                   Link = items.Element("link") != null ? items.Element("link").Value : "",
                                   Description = items.Element("description") != null ? items.Element("description").Value : "",
                                   Guid = (items.Element("guid") != null ? items.Element("guid").Value : "")
                               }
                   };
        }
    }
    public class Item
    {
        public string Title { set; get; }
        public string Link { set; get; }
        public string Description { set; get; }
        public string Guid { get; set; }
    }
}
